package com.example.native_view

import android.content.Context
import android.graphics.Color
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.TextView
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        flutterEngine
            .platformViewsController
            .registry
            .registerViewFactory("native-text-view", NativeTextViewFactory())
    }
}

class NativeTextViewFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
    override fun create(context: Context, id: Int, args: Any?): PlatformView {
        val params = args as? Map<String, Any>
        val text = params?.get("text") as? String ?: "默认文本"
        return NativeTextView(context, text)
    }
}

class NativeTextView(private val context: Context, private val text: String) : PlatformView {

    private val view = TextView(context).apply {
        setBackgroundColor(Color.BLUE)
        setTextColor(Color.WHITE)
        textSize = 16f
        gravity = Gravity.CENTER
        text = this@NativeTextView.text
    }

    init {
        Log.d("NativeTextView", "NativeTextView created")
    }

    override fun getView(): View {
        return view
    }

    override fun dispose() {
        Log.d("NativeTextView", "NativeTextView disposed")
    }
}

